//
//  ViewController.m
//  QQ聊天
//
//  Created by 伍银荣 on 2021/6/5.
//  Copyright © 2021 com.example. All rights reserved.
//

#import "ViewController.h"
#import "Messages.h"
#import "MessageCell.h"
#import "MessagesFrame.h"

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *messagesArr;

//@property (nonatomic, assign) CGFloat rowHeight;
@property (strong, nonatomic) IBOutlet UITextField *textField;

@end

@implementation ViewController

-(NSMutableArray *)messagesArr {
    if (!_messagesArr) {
        NSArray *arr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"message.plist" ofType:nil]];
        NSMutableArray *mArr = [NSMutableArray array];
        for (NSDictionary *dict in arr) {
            MessagesFrame *frameModel = [[MessagesFrame alloc]init];
            Messages *model = [Messages messagesWithDictionary:dict];
            //获取上一条数据模型的time
            Messages *lastMessage = (Messages *)[[mArr lastObject] messages];
            if ([model.time isEqualToString:lastMessage.time]) {
                model.hideTime = YES;
            }
            [mArr addObject:frameModel];
            frameModel.messages = model;
        }
        _messagesArr = mArr;
    }
    return _messagesArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //这是cell不可点击
    _tableView.allowsSelection = NO;
    _tableView.backgroundColor = [UIColor colorWithRed:236.0 / 255.0 green:236.0 / 255.0 blue:236.0 / 255.0 alpha:1.0];
    
    //监听键盘状态发生改变
    //UIKeyboardWillChangeFrameNotification: 键盘的位置尺寸即将发生改变
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
}

- (void)keyboardWillChangeFrame:(NSNotification *)noteInfo {
    
    NSLog(@"----noteInfo = %@",noteInfo);
    NSLog(@"通知的名称:%@",noteInfo.name);
    NSLog(@"发送监听的对象:%@",noteInfo.object);
    NSLog(@"通知的内容:%@",noteInfo.userInfo);
    
    //让当前self.view向上平移一个键盘的高度
    
    CGRect rectEnd = [noteInfo.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardY = rectEnd.origin.y;
    CGFloat transformValue = keyboardY - self.view.frame.size.height;
    [UIView animateWithDuration:0.25 animations:^{
       //键盘弹出时改变键盘的坐标
        self.view.transform = CGAffineTransformMakeTranslation(0, transformValue);
    }];
    
    //只要键盘的高度一发生改变,就将tableViewCell的最后一行滚动到最上面
    [self scrollToTop];
    
    /*
     在iPhone X之后的机型存在设置scroolView的宽高都是屏幕的宽高,但是运行出来会发现scrollView偏移了一部分,
     刚好偏移的是状态栏的高度(44),因此需要将这个view网上提一下,覆盖状态栏,充满整个屏幕
    */
    
    
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.messagesArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessagesFrame *frameModel = self.messagesArr[indexPath.row];
    static NSString *ID = @"message_cell";
    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[MessageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    cell.messagesFrame = frameModel;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessagesFrame *frameModel = self.messagesArr[indexPath.row];
    return frameModel.rowHeight;
}

//因为是当前控制器的view监听的键盘弹出,所以需要当前控制器的view移除通知
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 即将拖拽tableView
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    //在即将拖拽tableView时将键盘隐藏
    //把键盘叫回去:让控制器管理的view结束编辑
    [self.view endEditing:YES];
}

#pragma mark - textfield的代理
//键盘的return按钮是否可以点击
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    //发送一条消息
    //获取textfield输入的文字
    NSString *text = textField.text;
    if (text == nil || text.length == 0) {
        return NO;
    }
    [self replyWithText:text andMessageType:MessagesTypeMe];
    //获取plist文件的内容
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"autoMessages.plist" ofType:nil]];
    NSString *otherText = @"你好呀!";
    for (NSString *str in dict) {
        NSLog(@"str = %@",str);
        if ([text containsString:str]) {
            otherText = dict[str];
            break;
        }
    }
    [self replyWithText:otherText andMessageType:MessagesTypeOther];
    
    
    return YES;
}

- (void)replyWithText:(NSString *)text andMessageType:(MessagesType)messageType {
    //发送一条消息
    //获取textfield输入的文字
//    if (text == nil || text.length == 0) {
//        return 0;
//    }
    //获取一个空的模型数据
    MessagesFrame *frameModel = [[MessagesFrame alloc]init];
    Messages *model = [[Messages alloc]init];
    //获取系统当前时间
    NSDate *date = [NSDate date];
    //创建时间格式化对象
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"今天 HH:mm";
    NSString *currentTime = [formatter stringFromDate:date];
    MessagesFrame *lastFrame = self.messagesArr.lastObject;
    NSString *lastTime = lastFrame.messages.time;
    //判断当前输入的时间和lastModel中的time是否一致
    if ([currentTime isEqualToString:lastTime]) {
        //如果一致,隐藏当前时间
        model.hideTime = YES;
    }
    model.time = currentTime;
    model.type = messageType;
    model.text = text;
    frameModel.messages = model;
    //将模型数据添加到集合中
    [self.messagesArr addObject:frameModel];
    //刷新tableView的数据
    [self.tableView reloadData];
    //将tableViewcell最后一行滚动到最上面
    [self scrollToTop];
}

//将tableViewcell最后一行滚动到最上面
- (void)scrollToTop {
    NSIndexPath *idxPath = [NSIndexPath indexPathForRow:self.messagesArr.count - 1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:idxPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
}



@end
